﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Modeling.Validation;
using Microsoft.VisualStudio.Modeling;

namespace DSLFactory.VSCTDesigner
{
    class ValidationHelper
    {
        internal static void NotNullOrEmpty(ValidationContext context, string value, string name, params ModelElement[] args)
        {
            if( string.IsNullOrEmpty(value) )
                context.LogError(String.Format("Value {0} must not be empty", name), "ERR001", args);
        }

        internal static void ValidId(ValidationContext context, string value, string name, params ModelElement[] args)
        {
            try
            {
                GuidSymbolHelper.ParseID(value);
            }
            catch
            {
                context.LogError(String.Format("Value {0} is not a valid id (integer)", name), "ERR002", args);
            }
        }

        internal static void NotZero(ValidationContext context, int value, string name, params ModelElement[] args)
        {
           if( value <= 0)
            {
                context.LogError(String.Format("Value {0} must a positive value greater than 0", name), "ERR006", args);
            }
        }

        internal static void ValidGuid(ValidationContext context, string value, params ModelElement[] args)
        {
            if( value != "Extern" )
            {
                try
                {
                    new Guid(value);
                }
                catch
                {
                    context.LogError("Invalid guid value.", "ERR003", args);
                }
            }
        }
        
        internal static void ValidateExternGuidExists(ValidationContext context, ExternCommand element)
        {
            if( element.Guid == null || element.ID == null )
                return;
            Guid guid = element.CommandTable.NativeCommandTable.FindSymbolGuid(element.Guid);
            if( guid == Guid.Empty )
                context.LogError("Undefined external guid " + element.Guid, "ERR007", element);
            else if( element.CommandTable.NativeCommandTable.GetIDSymbols(guid).FirstOrDefault(id=> id==element.ID)==null)
                context.LogError("Undefined external id " + element.Guid + "/" + element.ID, "ERR007", element);
        }

        internal static void MustHaveStrings(ValidationContext context, CommandWithIcon element)
        {
            if( element.Strings.Count == 0 )
                context.LogError("Element must have at least one string definition", "ERR004", element);
        }

        internal static void MustHaveButtonText(ValidationContext context, StringDef element)
        {
            if( String.IsNullOrEmpty(element.ButtonText) )
                context.LogError("String definition must have a button text", "ERR005", element);
        }
    }
}
